<?php
/**
 * Created by PhpStorm.
 * User: 戎大富
 * Date: 2020/2/19
 * Time: 18:03
 */
namespace app\business\controller;
use think\Db;
class My extends Base {
    /**
     * 异地登录验证
     * @return string|void
     */
    public function _initialize()
    {
//        header('Access-Control-Allow-Origin:*');
//        extract(input());
//        if($user_id != 0){
//            $auth = $this->checkAll($user_id,$time,$value,$reqKey);
//            if($auth == 112){
//                echo json_encode(['status'=>301,'msg'=>$this->otherLogin]);
//                exit;
//            }elseif($auth == 110){
//                echo json_encode(['status' => 302, 'msg' => $this->frost]);
//                exit;
//            }elseif($auth == 1103){
//                echo json_encode(['status' => 303, 'msg' => $this->del]);
//                exit;
//            }
//        }

    }

    /**
     * 商户信息
     * `s_status` int(1) DEFAULT '4' COMMENT '1是审核中  2是正常(通过)   3是拒绝  4是未认证',
     *   `s_dl_status` int(1) DEFAULT '1' COMMENT '1未认证  2待审核 3审核通过 4审核不通过',
     * @return \think\response\Json
     */
    public function userInfo(){
        extract(input());
        $where['s_id'] = $user_id;
        $res = Db::table('up_shops')->where($where)->find();
        $dl_acc = [];
        if($res['s_dl_status'] == 3){
            $dl_acc = Db::name('dl')
                ->where(['d_f_id'=>$user_id])
                ->field('dl_account,password')
                ->find();
        }
        if($res['s_image']){
            $res['s_image'] = explode(',',$res['s_image']);
        }
        if($res['s_dl_sheng']){
            $res['s_dl_sheng_str'] = Db::table('up_area')->where('district_id',$res['s_dl_sheng'])->value('district');
            $res['s_dl_shi_str'] = Db::table('up_area')->where('district_id',$res['s_dl_shi'])->value('district');
            $res['s_dl_qu_str'] = Db::table('up_area')->where('district_id',$res['s_dl_qu'])->value('district');
        }
        return json(array('status'=>200,'msg'=>$res,'dl_acc'=>$dl_acc));

    }
    /**
     * 明细
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function consumeDetail(){
        extract(input());
        $data = Db::name('shop_apply')
            ->where(['shop_id'=>$user_id])
            ->order ('shop_apply_id desc')
            ->page ($page,20)
            ->select();
        return json(array('status'=>200,'msg'=>$data));
    }
    /**
     * 修改商户信息
     * @return \think\response\Json
     */
    public function userInfoEdit(){
        extract(input());
        $param['s_name'] = $name;
        $param['s_jianjie'] = $jianjie;
        $param['s_address'] = $s_address;
        $param['s_update_time'] = date('Y-m-d H:i:s');
        $param['s_sheng'] = $s_sheng;
        $param['s_shi'] = $s_shi;
        $param['s_qu'] = $s_qu;
//        $param['s_lon'] = $s_lon;
//        $param['s_lat'] = $s_lat;
        if($s_thumb != ''){
            $param['s_thumb'] = $s_thumb;
        }
        if($s_image != ''){
            $param['s_image'] = trim($s_image,',');
        }
        $res = Db::name('shops')->where('s_id',$user_id)->update($param);
        if($res){
            $shop = Db::name('shops')->where('s_id',$user_id)->find();
            return json(array('status'=>200,'msg'=>$shop));
        }else{
            return json(array('status'=>0,'msg'=>"修改失败"));
        }

    }
    /**
     * 认证
     * @return \think\response\Json
     */
    public function approve(){
        extract(input());
        $name = input('param.company');
        $zizhi = input('param.zizhi');
        $three = input('param.three');
        $code = input('param.code');
        $contact_name = input('param.username');
        $contact_phone = input('param.phone');
        $d = Db::name('shops')
            ->where('s_id',$user_id)
            ->field (['s_id','s_code','s_code_time','s_code_status'])
            ->find();
        if($d['s_code_status'] == 1 || $d['s_code'] == ''){
            return json(['code'=>100,'msg'=>'请先发送验证码']);
        }
        $t = time() - $d['s_code_time'];
        if($t >= 600){
            return json(['code'=>100,'msg'=>'验证码失效']);
        }
        if($code != $d['s_code']){
            return json(['code'=>100,'msg'=>'验证码错误']);
        }
        $param = [
            's_name'=>$name,
            's_zizhi'=>$zizhi,
            's_three'=>$three,
            's_contact_name'=>$contact_name,
            's_contact_phone'=>$contact_phone,
            's_update_time'=>date('Y-m-d H:i:s'),
            's_tj_time'=>date('Y-m-d H:i:s'),
            's_code_status'=>1,
            's_status'=>1
        ];
        $res = Db::name('shops')->where('s_id',$user_id)->update($param);
        if($res){
            $shop = Db::name('shops')->where('s_id',$user_id)->find();
            return json(array('status'=>200,'msg'=>$shop));
        }else{
            return json(array('status'=>0,'msg'=>"修改失败"));
        }

    }
    /**
     * 代理商
     * @return \think\response\Json
     */
    public function dailiAsk(){
        extract(input());
        $data['s_dl_name'] = input('param.username');
        $data['s_dl_phone'] = input('param.phone');
        $data['s_dl_sheng'] = input('param.sheng');
        $data['s_dl_shi'] = input('param.shi');
        $data['s_dl_qu'] = input('param.qu');
        $data['s_dl_level'] = input('param.level');
        $data['s_dl_content'] = input('param.content');
        $data['s_dl_status'] = 2;
        $data['s_dl_time'] = date('Y-m-d H:i:s');
        if(input('param.level') == 1){
            if(!input('param.sheng')){
                return json(['status' => 100, 'msg' => '省不能为空']);
            }
        }
        if(input('param.level') == 2){
            if(!input('param.sheng') || !input('param.shi')){
                return json(['status' => 100, 'msg' => '省市不能为空']);
            }
        }
        if(input('param.level') == 3){
            if(!input('param.sheng') || !input('param.shi') || !input('param.qu')){
                return json(['status' => 100, 'msg' => '省市区不能为空']);
            }
        }
        $res = Db::table('up_shops')->where('s_id',$user_id)->update($data);
        if($res){
            $shop = Db::name('shops')->where('s_id',$user_id)->find();
            return json(array('status'=>200,'msg'=>$shop));
        }else{
            return json(array('status'=>0,'msg'=>"操作失败，请刷新重试"));
        }

    }
//    public function feedback(){
//            extract(input());
//        $data = [
//            'f_user_id' => $user_id,
//            'feedback_content' => $content,
//            'feedback_time' => date('Y-m-d H:i:s'),
//        ];
//        $res = Db::table('up_feedback')->insert($data);
//        if($res){
//            return json(array('status'=>200,'msg'=>"成功"));
//        }else{
//            return json(array('status'=>0,'msg'=>"失败"));
//        }
//
//    }
    /**
     * 修改密码
     * @return mixed|\think\response\Json
     */
    public function updatePwd(){
        extract(input());
        $user = Db::name('shops')
            ->where('s_phone',$phone)
            ->field(['s_id','s_phone'])
            ->find();
        if(empty($user)){
            return json(['status'=>0,'msg'=>'该手机号尚未注册']);
        }
        //验证密码
        if($pwd != $surepwd) {
            return json(['status' => 0, 'msg' => '两次输入的密码不一致，请重新输入']);
        }
        $d = Db::name('shop_phonecode')->where(['phone'=>$phone,'status'=>0])->find();
        if(empty($d)){
            return json(['status'=>0,'msg'=>'请先发送验证码']);
        }
        $t = time() - $d['time2'];
        if($t >= 600){
            return json(['status'=>0,'msg'=>'验证码失效']);
        }
        if($code != $d['code']){
            return json(['status'=>0,'msg'=>'验证码错误']);
        }
        // 启动事务
        Db::startTrans();
        try{
            Db::name('shop_phonecode')->where(['phone'=>$phone])->setField ('status',1);
            Db::name('shops')->where(['s_phone'=>$phone])->update(['s_password'=>md5($pwd),'s_update_time'=>date('Y-m-d H:i:s')]);
            // 提交事务
            $user = Db::name('shops')
                ->where('s_phone',$phone)
                ->find();
            Db::commit();
            return json(['status'=>200,'msg'=>$user]);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return json(['status'=>100,'msg'=>'密码重置失败']);
        }
    }
    /**
     * 注销
     * @return mixed|\think\response\Json
     */
    public function delshop(){
        extract(input());
        $user = Db::name('shops')
            ->where('s_phone',$phone)
            ->field(['s_id','s_phone'])
            ->find();
        if(empty($user)){
            return json(['status'=>0,'msg'=>'该手机号尚未注册']);
        }
        $d = Db::name('shop_phonecode')->where(['phone'=>$phone,'status'=>0])->find();
        if(empty($d)){
            return json(['status'=>0,'msg'=>'请先发送验证码']);
        }
        $t = time() - $d['time2'];
        if($t >= 600){
            return json(['status'=>0,'msg'=>'验证码失效']);
        }
        if($code != $d['code']){
            return json(['status'=>0,'msg'=>'验证码错误']);
        }
        // 启动事务
        Db::startTrans();
        try{
            Db::name('shop_phonecode')->where(['phone'=>$phone])->setField ('status',1);
            Db::name('shops')->where(['s_phone'=>$phone])->update(['s_sta'=>2]);
            Db::commit();
            return json(['status'=>200,'msg'=>'ok']);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return json(['status'=>100,'msg'=>'密码重置失败']);
        }
    }
    /**
     * 更改手机号第一步
     * @return bool
     * phone  手机号
     * code  验证码
     */
    public function changeFirst()
    {
        extract(input());
        $phone = trim(input('phone'), ' ');
        $code = trim(input('code'), ' ');

        if($phone == '') {
            return json(['status' => 0, 'msg' => '请输入手机号码']);
        }
        if($code == '') {
            return json(['status' => 0, 'msg' => '请输入验证码']);
        }
        $userInfo = Db::name('shops')
            ->where('s_phone',$phone)
            ->find();
        if(empty($userInfo)) {
            return json(['status' => 0, 'msg' => '该账号不存在']);
        }

        $res = Db::name('shop_phonecode')->where(['phone'=>$phone])->find();
        if($code != $res['code']) {
            return json(['status' => 0, 'msg' => '验证码错误']);
        }
        $now = time();
        if($now - $res['time2'] >= 600) {
            return json(['status' => 0, 'msg' => '验证码超时']);
        }
        if($res['status'] == 1) {
            return json(['status' => 0, 'msg' => '验证码已使用']);
        }

        if($userInfo['s_sta'] == 2){
            return json(['status'=>0,'msg'=>'该商户已被注销']);
        }
        Db::table('up_phonecode')->where('id', $res['id'])->update(['status' => 1]);
        return json(['status' => 200, 'msg' => $userInfo]);
    }

    /**
     * 更改手机号第二步
     * @return bool
     * $phone  手机号
     * $code  验证码
     */
    public function changeSecond()
    {
        extract(input());
        $user = Db::name('shops')
            ->where('s_phone',$phone)
            ->field(['s_id','s_phone'])
            ->find();
        $shop_son = Db::name('role_name')
            ->where('role_user',$phone)
            ->field(['role_status','f_id','r_s_id','role_password'])
            ->find();
        if(!empty($user) || $shop_son){
            return json(['status'=>0,'msg'=>'该手机号已注册']);
        }
        $d = Db::name('shop_phonecode')->where(['phone'=>$phone,'status'=>0])->find();
        if(empty($d)){
            return json(['status'=>0,'msg'=>'请先发送验证码']);
        }
        $t = time() - $d['time2'];
        if($t >= 600){
            return json(['status'=>0,'msg'=>'验证码失效']);
        }
        if($code != $d['code']){
            return json(['status'=>0,'msg'=>'验证码错误']);
        }


        $token = md5(date('YmdHis') . rand(100000, 999999));
        $update = [
            's_token' => $token,
            's_phone' => $phone,
            's_update_time' => date('Y-m-d H:i:s')
        ];
        $res = Db::table('up_shops')
            ->where('s_id', $user_id)
            ->update($update);
        if($res){
            $userInfo = Db::table('up_shops')->where('s_id', $user_id)->find();
            return json(['status' => 200, 'msg' => $userInfo]);
        }else{
            return json(['status' => 0, 'msg' => '失败']);
        }
    }

    /**
     * 充值
     * @return string
     */
    public function recharge()
    {
        extract(input());
        $number = time() . rand(1000000,9999999);
        $param = [
            'order_number'=>$number,
            'order_shopid'=>$user_id,
            'order_user_pay'=>$money,
            'order_coin'=>$money*10,
            'order_remark'=>'充值',
            'order_type'=>$pay_type,
            'order_time'=>date('Y-m-d H:i:s')
        ];
        Db::name('order')->insert ($param);
        $money = 0.01;
        if($pay_type == 2){
            $order = array();
            $order['body'] = '充值'; // 描述
            $order['total_fee'] = $money*100; // 订单金额
            $order['out_trade_no'] = $number; // 订单号
            $order['product_id'] = ''; // 产品ID
            $order['trade_type'] = 'APP'; // 类型
            $mww_weixinpay =  new \app\business\controller\Weixin();
            $respont = $mww_weixinpay->WeChatPayReady($order);
            return json_encode(['status'=>200,'msg'=>$respont]);
        }elseif($pay_type == 1){
            $mww_alipay =  new \app\business\controller\Ali();
            $respont = $mww_alipay->getParam($number, $money, '充值', '充值');
            return json_encode($respont);
        }
    }
    /**
     * uploadLocality图片上传至本地&压缩
     */
    public function uploadLocality(){
        $file = request()->file('file');
        $yasuo = false;
        if (!$file->checkSize(1024 * 1024 * 5)) { //大于5M就压缩一下
            $yasuo = true;
        }
        $dir = ROOT_PATH . 'public' . DS . 'uploads/images';
        if(!file_exists($dir)){
            //检查是否有该文件夹，如果没有就创建，并给予最高权限
            mkdir($dir, 0700,true);
        }
        $info = $file->move($dir);
        if($info){
            $newName = $info->getSaveName();
            //压缩图片
            if ($yasuo === true) { //大于5M就压缩一下
                $this->image_png_size_add($dir . '/' . $newName, $dir . '/' . $newName);
            }
            return json(array('status'=>200,'msg'=>'http://'.$_SERVER['SERVER_NAME']."/uploads/images/{$newName}"));

//            echo "/uploads/images/{$newName}";
        }else{
//            echo $file->getError();
            return json(array('status'=>201,'msg'=>$file->getError()));
        }
    }
}